import os
import sys

from PyQt5.QtWidgets import QApplication
from PyQt5.QtWidgets import QInputDialog
from zhdate import ZhDate

from config_manager import ConfigManager
from core.painter import drawMain
from core.pipeManager import PipeManager as SingleChecker
from data.manager import CsvManager
from ui.main import UIModel
from utils.define import FILE_DATA_PATH
from utils.tools import showMessageBox


class InvoicePrinter:
    def __init__(self):
        self.config = ConfigManager(self)
        self._customer = None
        self._csv_path = self.init_csv_path()

        self.dataModel = CsvManager(self)

        self.ui = UIModel(self)
        self.ui.btnPrint.clicked.connect(self.printAndSave)
        # 修改为不关心返回值的 lambda 函数
        self.ui.btnSave.clicked.connect(lambda: (self.save(), None)[1])
        self.ui.btnAddInCustomer.clicked.connect(self.addInCustomer)
        self.ui.btnAddOutCustomer.clicked.connect(self.addOutCustomer)
        self.ui.onNameChanged.connect(self.setCurCustomer)

        self.checker = SingleChecker()
        self.checker.message_received.connect(self.activateWindow)
        self.checker.start()

        # 测试代码
        # self.setIDCount(self.getIDCount())

    def init_csv_path(self):
        # 通过农历年份生成文件夹
        year_path = os.path.join(FILE_DATA_PATH, str(ZhDate.today().lunar_year))
        if not os.path.exists(year_path):
            os.mkdir(year_path)
        return year_path

    @property
    def csv_path(self):
        return self._csv_path

    @property
    def customer(self):
        return self._customer

    def setCurCustomer(self, name):
        self._customer = name

    @property
    def customers(self):
        return self.config.customers

    def getpriceFunc(self):
        return self.config.getpriceFunc()

    def getCsvModel(self):
        return self.dataModel.getCsvModel()

    def getDate(self):
        return self.ui.getDate()

    def getItems(self):
        return self.ui.getItems()

    def getNum2NameDict(self):
        return self.config["num2Name"]

    def getfontSize(self):
        return self.config["fontSize"]

    def getUserName(self):
        return self.config["user"]

    def getUserMobile(self):
        return self.config["mobile"]

    def getIDCount(self):
        return self.config["IDCount"]

    def setIDCount(self, idCount):
        self.config.setIDCount(idCount)

    def onIDCountChanged(self, idCount):
        self.ui.onIDChanged(idCount)

    def printAndSave(self):
        items = self.save()
        if items is None:
            return

        drawMain(self.ui.mainWindow, self.ui.getInfo(), items, self.getfontSize())

        self.config.addIDCount()

    def save(self):
        if self.customer is None or self.customer == "":
            showMessageBox("请先选择客户")
            return None

        items = self.ui.getItems()

        checkFlag = self.config.save_config(items)
        if not checkFlag:
            return None

        result = self.dataModel.save(items)
        if result:
            self.ui.onSave()

        return result and items or None

    def print(self, items):
        drawMain(self.ui.mainWindow, self.ui.getInfo(), items, self.getfontSize())

    def addInCustomer(self):
        self.addCustomer("内账")

    def addOutCustomer(self):
        self.addCustomer("外账")

    def addCustomer(self, dirName):
        dialog = QInputDialog()
        dialog.setWindowTitle("新增{}客户".format(dirName))
        dialog.setLabelText("请输入{}客户名".format(dirName))
        dialog.setOkButtonText("确认")
        dialog.setCancelButtonText("取消")

        result = dialog.exec_()
        name = dialog.textValue()
        if result == QInputDialog.Accepted:
            if self.config.addCustomer(dirName, name) and self.dataModel.addCustomer(dirName, name):
                self.ui.onAddCustomer(name)

    def activateWindow(self):
        self.ui.mainWindow.showNormal()
        self.ui.mainWindow.activateWindow()
        self.ui.mainWindow.raise_()

    def close(self):
        if self.dataModel.close():
            self.config.save_config()
            self.checker.stop()
            return True
        return False

if __name__ == "__main__":
    app = QApplication(sys.argv)

    if SingleChecker.already_exists():
        sys.exit(0)  # Exit if there's already an instance running.
    else:
        invoicePrinter = InvoicePrinter()

    sys.exit(app.exec_())
